//
//  SneakyController.m
//  SneakyBastard
//
//  Created by Krist Menina on 9/13/09.
//  Copyright 2009 Hello Wala Studios. All rights reserved.
//

#import "Controller.h"

@interface Controller (Private)
- (void)refreshTable;
- (BOOL)isConnected;
- (void)startTimer;
- (void)stopTimer;
- (void)timerIncrement:(NSTimer *)aTimer;
- (void)loadSnapshotsStart:(NSString *)rpath;
- (void)sendMailStart:(id)sender;
- (BOOL) useSmtpSettings;
- (void)alertTimeOut;
@end

#define	TIMEOUT 30
#define CANCELTIMEOUT 200

@implementation Controller

- (id) init
{
	NSLog(@"init");
	
	self = [super init];
	
	NSFileManager *fm = [NSFileManager defaultManager];
	snapCount = 0;
	sbDir = @"temp/";
	path = NSHomeDirectory();
	fullPath =  [NSString stringWithFormat:@"%@/%@",path,sbDir];	
	[fm changeCurrentDirectoryPath:path]; 
	BOOL isDir,b;
	b = [fm fileExistsAtPath:sbDir isDirectory:&isDir];

	if(b){
		tableRecord = [[NSMutableArray alloc] init];
		queue = [[NSOperationQueue alloc] init];
	}else{
		BOOL dirOk;
		NSString *username = NSUserName();
		NSMutableDictionary *attr = [NSMutableDictionary dictionary]; 
		[attr setObject:username forKey:NSFileOwnerAccountName]; 
		[attr setObject:@"staff" forKey:NSFileGroupOwnerAccountName]; 
		[attr setObject:[NSNumber numberWithInt:480] forKey:NSFilePosixPermissions];
		
		dirOk = [fm createDirectoryAtPath:sbDir 
							   attributes:attr];

	}
	// retain or use getter/setter
	[sbDir retain];
	[path retain];
	[fullPath retain];
	
	NSNotificationCenter *center = [[NSWorkspace sharedWorkspace] notificationCenter];
	[center addObserver:self 
			   selector:@selector(machineDidWake:)
				   name:NSWorkspaceDidWakeNotification 
				 object:NULL];
	
	//BOOL ok = [self isConnected];
	return self;
}

- (void)awakeFromNib
{
	[self loadSnapshotsStart:fullPath];	
	
	[self quickSnap:self];	
	
	
}

- (NSApplication *)application
{
	

	return NSApp;
}

- (void) machineDidWake:(NSNotification *)notification{
	NSLog(@"sneaky wake up!");
	[self quickSnap:self];	
	[self performSelector: @selector(loadSnapshotsStart:)
				withObject:fullPath
				afterDelay:5];
}

- (void)dealloc
{
	NSLog(@"dealloc");
	[[NSStatusBar systemStatusBar] removeStatusItem:_statusItem];
	[_statusItem release];
	[timer release];
	[sneakyCam release];
	[super dealloc];
}

- (void)loadSnapshotsStart:(NSString *)rpath
{
	
	[tableRecord removeAllObjects];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleLoadedSnapshots:) name:LoadSnapshotsFinish object:nil];	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleNoSnapshots:) name:NoSnapshotsFound object:nil];	
	
	[queue cancelAllOperations];
	
	// start the GetPathsOperation with the root path to start the search
	GetSnapshots* getSnaps = [[GetSnapshots alloc] initWithRootPath:rpath operationClass:nil queue:queue];
	
	[queue addOperation: getSnaps];	// this will start the "GetPathsOperation"
	[getSnaps release];	

	
}

- (void)anyThread_handleLoadedSnapshots:(NSNotification *)note
{
	// update our table view on the main thread
	//[[NSNotificationCenter defaultCenter] removeObserver:self name:LoadSnapshotsFinish object:nil];	
	
	[self performSelectorOnMainThread:@selector(updateSnapTable:) withObject:note waitUntilDone:NO];


}

- (void)anyThread_handleNoSnapshots:(NSNotification *)note
{
	NSLog(@"no snapshots");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:LoadSnapshotsFinish object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NoSnapshotsFound object:nil];
	[self performSelectorOnMainThread:@selector(updateSnapTable:) withObject:nil waitUntilDone:NO];
}

- (void)sendMailStart:(id)sender
{
	
	if([tableRecord count] <= 0){
		NSLog(@"Nothing to send");
	}else if(![self useSmtpSettings]){
		NSLog(@"incomplete smtp settings");

	}else if(![self isConnected]){
		NSLog(@"network is not connected");
	}else{
		// setup smtp credentials
		NSMutableDictionary *authInfo = [NSMutableDictionary dictionary];
		[authInfo setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"smtpUsername"] forKey:EDSMTPUserName];
		[authInfo setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPassword"] forKey:EDSMTPPassword];
		
		// setup email header
		NSMutableDictionary *headerFields = [NSMutableDictionary dictionary];
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailFrom"] forKey:@"From"]; 
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailAddress"] forKey:@"To"]; 	
		[headerFields setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"emailSubject"] forKey:@"Subject"];
		
		// setup attachments
		id item = NULL;
		NSEnumerator* iterator = [tableRecord objectEnumerator]; 
		NSMutableArray* attachmentList = [NSMutableArray array];
		NSMutableString* imgPath;
		while (item=[iterator nextObject]) 
		{
			imgPath = [NSString stringWithFormat:@"%@/%@",fullPath,[item valueForKey:@"name"]];
			NSData *imgData = [[NSData alloc] initWithContentsOfFile:imgPath];
			[attachmentList addObject:[EDObjectPair pairWithObjects:imgData:[imgPath lastPathComponent]]];
		}
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleEmailSent:) name:EmailSentSuccess object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyThread_handleEmailSentFail:) name:EmailSentFail object:nil];
		
		[queue cancelAllOperations];
		
		[self startTimer];		
		MailOperation* mailSnaps = [[MailOperation alloc] initWithRootPath:fullPath queue:queue attachList:attachmentList header:headerFields auth:authInfo];
		
		[queue addOperation: mailSnaps];	


	}
}



- (void)anyThread_handleEmailSent:(NSNotification *)note
{
	NSLog(@"Email SentOK ");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentSuccess object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentFail object:nil];
	[self performSelectorOnMainThread:@selector(deleteSnapshots) withObject:nil waitUntilDone:NO];
}

- (void)anyThread_handleEmailSentFail:(NSNotification *)note
{
	NSLog(@"Email Sent Failed");
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentSuccess object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:EmailSentFail object:nil];
	NSLog(@"mail sending FAIL");
	[self performSelectorOnMainThread:@selector(alertSendFail) withObject:nil waitUntilDone:NO];
}

- (BOOL) useSmtpSettings
{
	//[[NSUserDefaults standardUserDefaults] boolForKey:@"overwriteSnapshot"]
	return ([[NSUserDefaults standardUserDefaults] stringForKey:@"smtpURL"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPort"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpUsername"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"smtpPassword"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"emailAddress"] != nil && [[NSUserDefaults standardUserDefaults] stringForKey:@"emailSubject"] != nil );
}


- (void)updateSnapTable:(NSNotification *)note
{
	
	if(note != nil){
		
		[tableRecord addObject:[note userInfo]];
		[self performSelectorOnMainThread:@selector(sendMailStart:) withObject:nil waitUntilDone:NO];
	}
	//[self refreshTable];
}

- (void)refreshTable
{

	int total = [tableRecord count];
	if(total){
		NSLog(@"%@ snapshots found",tableRecord);
	}else{
		NSLog(@"No snapshots found");
	}
	
	//[self stopTimer];
	
}

- (void)startTimer
{

	secs = 0;
	to = 0;
	timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
											 target:self 
										   selector:@selector(timerIncrement:) 
										   userInfo:0 
											repeats:YES]; 
	
	
	
	
}

- (void)stopTimer
{

	
	[timer invalidate];
	timer = nil;
	
	
}

- (void)setTimer:(int)seconds
{
	NSString* strSec = [NSString stringWithFormat:@"%d",seconds];
	//[labelTimer setStringValue:strSec];
	[strSec release];
}

- (void)timerIncrement:(NSTimer *)aTimer
{

	NSLog(@"secs: %d %d",secs,[self isConnected]);
	secs++;
	if(![self isConnected]){
		to++;
		if(to >= TIMEOUT){
			[self alertTimeOut];
		}
	}else{
		to = 0;
		if(secs >= CANCELTIMEOUT){
			[self alertTimeOut];
		}
	}
	//[self setTimer:secs];
	//[labelTimer setStringValue:[NSString stringWithFormat:@"%d",secs]];
}

- (void)alertSendFail
{
	
	[self stopTimer];	
}

- (void)alertTimeOut
{
	[self stopTimer];
	
	/*NSAlert *alert = [NSAlert alertWithMessageText: @"Connection Timeout"
									 defaultButton: @"OK"
								   alternateButton: nil
									   otherButton: nil
						 informativeTextWithFormat: @"Network Connection timed out"];
	[alert beginSheetModalForWindow: [self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];	*/
	NSLog(@"Connection Timeout");
	
}

- (void)deleteSnapshots
{
	[self stopTimer];
	
	id item = NULL;
	NSEnumerator* iterator = [tableRecord objectEnumerator]; 	
	NSFileManager* fileManager = [NSFileManager defaultManager];
	NSMutableString* imgPath;
	//int total = [self numberOfRowsInTableView:tableView];

	while (item=[iterator nextObject]) 
	{
		imgPath = [NSString stringWithFormat:@"%@%@",fullPath,[item valueForKey:@"name"]];
		[fileManager removeItemAtPath:imgPath error:NULL];
		
		NSLog(@"delete --> %@",imgPath);
	}
	[tableRecord removeAllObjects];

	
}


- (void) actionQuit:(id)sender {
	[NSApp terminate:sender];
}


- (void) quickSnap:(id)sender{
	
	NSString *fn;
	
	if([[NSUserDefaults standardUserDefaults] boolForKey:@"overwriteSnapshot"] == 1){
		NSDate *now = [NSDate date];
	
		NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
		[formatter setDateFormat:@"MMddYY_HHmmss"];
		NSString* formattedDateString;
		formattedDateString = [formatter stringFromDate:now];		
		
		fn = [NSString stringWithFormat:@"bbb_%@.jpg",formattedDateString];
	} else {
		fn = @"bbb.jpg";
		
	}
	sneakyCam = [[SneakyCamera alloc] init] ;
	[sneakyCam setImgPath:[path stringByAppendingFormat:@"/%@",sbDir]];
	[sneakyCam setImgName:fn];
	
}


- (BOOL)isConnected
{
    Boolean success;
    BOOL okay;
    SCNetworkConnectionFlags status;
	
    success = SCNetworkCheckReachabilityByName("www.apple.com", 
											   &status);
	
    okay = success && (status & kSCNetworkFlagsReachable) && !(status & 
															   kSCNetworkFlagsConnectionRequired);
	
    if (!okay)
    {
        success = SCNetworkCheckReachabilityByName("www.w3.org", 
												   &status);
		
        okay = success && (status & kSCNetworkFlagsReachable) && 
		!(status & kSCNetworkFlagsConnectionRequired);
		NSLog(@"No net");
    }else{
		NSLog(@"Net OK");
	}
	
	
    return okay;
}

- (id)statusItem
{
	if (_statusItem == nil)
	{
		//NSMenu		*menu;
		//NSMenuItem *bmenu;
		NSImage *img;
		

		img = [NSImage imageNamed:@"smile"];
		_statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
		[_statusItem setImage:img];
		[_statusItem setHighlightMode:YES];
		[_statusItem setEnabled:YES];
		

		[_statusItem setMenu:menuItemMenu];
		
		[img release];
		//[menu release];		

		
	}
	return _statusItem;
}


- (IBAction) setOverwriteSnapshot:(id)sender{
	
	NSLog(@"overwrite snapshot %d",[[NSUserDefaults standardUserDefaults] boolForKey:@"overwriteSnapshot"]);
	
}

- (NSString *)versionString
{
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSDictionary *infoDict = [mainBundle infoDictionary];
	
    //NSString *mainString = [infoDict valueForKey:@"CFBundleShortVersionString"];
    NSString *subString = [infoDict valueForKey:@"CFBundleVersion"];
    //return [NSString stringWithFormat:@"Version %@ (%@)", mainString, subString];
	return [NSString stringWithFormat:@"Version %@", subString];
}

- (NSString*)copyrightString
{
    return @"Copyright © 2010 \nKrist Menina\nkrist@hellowala.org";
}
- (float)appNameLabelFontSize;
{
    return 16.0;
}




- (IBAction) aboutWindowController: (id) sender
{
	[aboutWindow setLevel:NSStatusWindowLevel];
	[aboutWindow makeKeyAndOrderFront:nil];
	[aboutWindow center];
	//[versionText setStringValue:[self printVersion]];	
}

- (IBAction) prefWindowController: (id) sender
{
	[prefWindow setLevel:NSStatusWindowLevel];
	[prefWindow makeKeyAndOrderFront:nil];
	[prefWindow center];

	//[versionText setStringValue:[self printVersion]];	
}

@end
